package org.renhj.rpc;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.renhj.common.RpcRequest;

public class RpcEncoder extends MessageToByteEncoder<Object> {

    private static final JSONSerializer jsonSerializer = new JSONSerializer();
;
    private final Class<?> clazz;


    public RpcEncoder() {
        this.clazz = RpcRequest.class;
    }

    public RpcEncoder(Class<?> clazz) {
        this.clazz = clazz;
    }


    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object object, ByteBuf byteBuf) throws Exception {
        if (clazz.isInstance(object)) {
            byte[] b = jsonSerializer.serialize(object);
            byteBuf.writeInt(b.length);
            byteBuf.writeBytes(b);
        }
    }
}
